﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;


namespace SmartBlast
{
    public partial class frmProducts : Form
    { 
        public static string TABLE_NAME = "Products";
        private static string[] HEADERS = new string[] { "Model", "Price","Quantity"};
        public static string[] FIELD_NAMES = new string[] { "Model", "Price", "Quantity" };
        private string[] fields;
        private DataTable productsDataTable;
        private bool editable = false;
        private DataBase_BUS databaseBUS;
        private Main main;

        public frmProducts(Main main)
        {
            InitializeComponent();
            databaseBUS = DataBase_BUS.getInstance();
            this.main = main;
        }

        private void btn_search_Click(object sender, EventArgs e)
        {
            collectFields();
            productsDataTable = databaseBUS.selectRecrordFromTable(TABLE_NAME, FIELD_NAMES, fields);
            refresh();
        }

        private void btn_add_Click(object sender, EventArgs e)
        {
            if (!noFieldsAreBlank())
                MessageBox.Show("\nPlease input all fields", "Missing Information", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            else
            {
                collectFields();
                try
                {
                   databaseBUS.insertRecordIntoTable(TABLE_NAME, fields);
                    clearTextBoxes();
                    showAll();
                }
                catch
                {
                    gridProducts.Visible = false;
                    lbl_NoResults.Visible = true;
                    lbl_NoResults.Text = "There is a product with the same name. \n Please select another";
                }

            }
        }

        private void btn_Clear_Click(object sender, EventArgs e)
        {
            clearTextBoxes();
        }

        private void btn_showAll_Click(object sender, EventArgs e)
        {
            showAll();
        }

        private void collectFields()
        {

            fields = new string[] { "'" + txtModel.Text + "'",txtPrice.Text, txtQuantity.Text };
        }

        private Boolean noFieldsAreBlank()
        {
            return (txtModel.Text != "" && txtPrice.Text != "" && txtQuantity.Text != "");
        }

        private void clearTextBoxes()
        {
            txtModel.Text = txtPrice.Text = txtQuantity.Text = "";
        }

        private void showAll()
        {
            productsDataTable = databaseBUS.selectRecrordFromTable(TABLE_NAME, null, null);
            refresh();
        }


        private void refresh()
        {
            if (productsDataTable.Rows.Count == 0)
            {
                gridProducts.Visible = false;
                lbl_NoResults.Visible = true;
            }
            else
            {
                lbl_NoResults.Visible = false;
                gridProducts.Visible = true;
                gridProducts.DataSource = productsDataTable;
                gridProducts.Columns[3].ReadOnly = true; //Changing the code of the component is not allowed
                for (int i = 3; i < gridProducts.ColumnCount; i++)
                    gridProducts.Columns[i].HeaderText = HEADERS[i - 3];
            }
        }

        private void gridProducts_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            string model = ((System.Windows.Forms.DataGridView)(sender)).CurrentRow.Cells[3].Value.ToString();
            int index = (((System.Windows.Forms.DataGridView)(sender)).CurrentCell).ColumnIndex;

            if (index == 0) //click on "edit"
            {
                ((System.Windows.Forms.DataGridView)(sender)).CurrentRow.DefaultCellStyle.ForeColor = Color.Red;
                editable = true;
            }

            else if (index == 1 && editable) //click on "save"
            {
                string price = ((System.Windows.Forms.DataGridView)(sender)).CurrentRow.Cells[4].Value.ToString();
                string quantity = ((System.Windows.Forms.DataGridView)(sender)).CurrentRow.Cells[5].Value.ToString();

                fields = new string[] {"'"+ model+"'",price , quantity};

                databaseBUS.updateRecordInTable(TABLE_NAME, FIELD_NAMES, fields, FIELD_NAMES[0], fields[0]);
                MessageBox.Show("The product was successfully updated");
                showAll();
                editable = false;
            }

            else if (index == 2) //click on "delete"
            {
                DialogResult dialogResult = MessageBox.Show("Are you sure you want to delete the product?", "Delete", MessageBoxButtons.YesNo);
                if (dialogResult == DialogResult.Yes)
                {
                    databaseBUS.deleteRecordFromTable(TABLE_NAME, FIELD_NAMES[0], "'"+model+"'");
                    MessageBox.Show("The product was successfully deleted");
                }

                showAll();
                
            }
        }


        private void txtQuantity_TextChanged(object sender, EventArgs e)
        {
            int threshold;
            bool success = int.TryParse(txtQuantity.Text, out threshold);
            String prevText = txtQuantity.Text.Substring(0, Math.Max(0, txtQuantity.Text.Length - 1));
            if (!success)
            {
                txtQuantity.Text = prevText;
            }
            else
            {
                txtQuantity.Text = threshold.ToString();
            }
        }


        private void btn_exit_Click(object sender, EventArgs e)
        {
            main.Show();
            this.Hide();
        }

        

        private void txtPrice_TextChanged(object sender, EventArgs e)
        {
            int price;
            bool success = int.TryParse(txtPrice.Text, out price);
            String prevText = txtPrice.Text.Substring(0, Math.Max(0, txtPrice.Text.Length - 1));
            if (!success)
            {
                txtPrice.Text = prevText;
            }
            else
            {
                txtPrice.Text = price.ToString();
            }
        }

        private void frmProducts_Load(object sender, EventArgs e)
        {
            this.CenterToScreen();
        }

    }
}
